package com.yiyuan.app.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.guaike.core.entity.result.Result;
import com.guaike.core.redis.context.ApiContext;
import com.yiyuan.app.entity.param.SysOssPresignedDTO;
import com.yiyuan.app.entity.result.AppUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileStorageService;
import org.dromara.x.file.storage.core.constant.Constant;
import org.dromara.x.file.storage.core.presigned.GeneratePresignedUrlResult;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author: zhangxilin
 * @Date: 2024/10/30
 */
@Slf4j
@RestController
@RequestMapping("/oss")
@Api(tags = "系统-OSS相关接口组")
@AllArgsConstructor
public class SysAliOssController {

    private final FileStorageService fileStorageService;

    @PostMapping("/generatePresignedUrl")
    @ApiOperation(value = "预签名URL")
    public Result<GeneratePresignedUrlResult> generatePresignedUrl(@Valid @RequestBody SysOssPresignedDTO param) {
        GeneratePresignedUrlResult uploadResult = fileStorageService
                .generatePresignedUrl()
                .setPath(buildUploadKey())
                .setMethod(Constant.GeneratePresignedUrl.Method.PUT)
                .setExpiration(DateUtil.offsetMinute(new Date(), 3))
                // 设置保存的文件名
                .setFilename(param.getFileName())
                .putHeadersAll(!CollectionUtils.isEmpty(param.getHeaders()), param.getHeaders())
                .putUserMetadataAll(!CollectionUtils.isEmpty(param.getUserMetadata()), param.getUserMetadata())
                .putQueryParamsAll(!CollectionUtils.isEmpty(param.getQueryParams()), param.getQueryParams())
                .putResponseHeadersAll(!CollectionUtils.isEmpty(param.getResponseHeaders()), param.getResponseHeaders())
                .generatePresignedUrl();
        log.warn("生成上传预签名 URL 结果：{}, param: {}", uploadResult, JSONObject.toJSONString(param));
        return Result.success().data(uploadResult).build();
    }

    private static String buildUploadKey() {
        AppUser currentUser = ApiContext.getCurrentUser();
        return LocalDateTimeUtil.format(LocalDateTime.now(), "yyyyMMddHHmmssSSS") + currentUser.getUserId() + "/";

    }

}
